package com.example.task;

import com.example.service.SkillGoodsService;
import com.example.service.impl.SkillGoodsServiceImpl;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @description 秒杀商品定时任务，将秒杀商品存入Redis，进行预热
 * @author aimi
 **/
@Slf4j
@Component
public class SkillGoodsTask {
    @Autowired
    private SkillGoodsService skillGoodsService;

    @PostConstruct
    public void init() {
        log.info("系统启动时，初始化定时任务");
        skillGoodsService.insertSkillGoods();
    }

    // 每个整点的前五分钟执行
    @Scheduled(cron = "0 55 * * * ?")
    public void insertSkillGoods(){
        log.info("执行预热秒杀商品定时任务");
        int[] beginHours = SkillGoodsServiceImpl.beginHours;
        int currHour = LocalDateTime.now().getHour();
        for (int hour : beginHours){
            // 如果当前时间是指定时间的前一个小时
            if(currHour == hour - 1){
                skillGoodsService.insertSkillGoods();
                break;
            }
        }
    }
}